package com.movie.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 简化版的JWT工具类，不使用复杂的加密算法
 */
@Component
public class JwtUtil {

    @Value("${jwt.expiration.ms}")
    private long expirationMs;

    // 从 token 中提取用户名
    public String extractUsername(String token) {
        // 简化处理，直接解码Base64并返回用户名
        try {
            String decoded = new String(Base64.getDecoder().decode(token));
            return decoded.split(":")[0];
        } catch (Exception e) {
            return null;
        }
    }

    // 生成简化的token
    public String generateToken(UserDetails userDetails) {
        // 简化的token生成，仅包含用户名和过期时间
        String username = userDetails.getUsername();
        long expiration = System.currentTimeMillis() + expirationMs;
        String tokenContent = username + ":" + expiration;
        return Base64.getEncoder().encodeToString(tokenContent.getBytes());
    }

    // 验证token是否有效
    public Boolean validateToken(String token, UserDetails userDetails) {
        try {
            String decoded = new String(Base64.getDecoder().decode(token));
            String[] parts = decoded.split(":");
            String username = parts[0];
            long expiration = Long.parseLong(parts[1]);

            // 检查用户名是否匹配且未过期
            return username.equals(userDetails.getUsername()) && expiration > System.currentTimeMillis();
        } catch (Exception e) {
            return false;
        }
    }
}